package com.simple.framework.utils;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.simple.framework.core.domain.dto.ColumnInfo;
import org.apache.commons.codec.Charsets;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Description Excel工具类
 * @Author xiaoke
 * @Date 2024/9/8 13:05
 * @Version 1.0
 */
public class EasyExcelUtil {

    /** 导出Excel文件
     * @param response 响应
     * @param dataList 数据
     * @param <T>      泛型
     */
    public static <T> void export(HttpServletResponse response, List<ColumnInfo> columns, List<T> dataList) throws IOException {
        //头部
        List<String> headNameList = new ArrayList<>();
        //字段
        List<String> fieldList = new ArrayList<>();

        for (ColumnInfo columnInfo : columns) {
            headNameList.add(columnInfo.getTitle());
            fieldList.add(columnInfo.getDataIndex());
        }
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding(Charsets.UTF_8.name());
        String fileName = URLEncoder.encode(UUID.randomUUID().toString(), Charsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //数据
        List<List<Object>> resultDataList = EasyExcelUtil.dataList(fieldList, JSON.parseArray(JSON.toJSONString(dataList)));
        EasyExcelFactory.write(response.getOutputStream()).sheet("sheet1").head(EasyExcelUtil.headList(headNameList)).doWrite(resultDataList);
    }

    /**
     * 封装表格标题
     *
     * @param headNameList 标题数据
     * @return 表格标题集合
     */
    public static List<List<String>> headList(List<String> headNameList) {
        List<List<String>> headList = new ArrayList<>();
        for (String headName : headNameList) {
            List<String> list = new ArrayList<>();
            list.add(headName);
            headList.add(list);

        }
        return headList;
    }

    /**
     * 封装导出字段的数据结构
     *
     * @param fieldList 字段
     * @param dataObj   数据集合
     * @return 字段值集合
     */
    public static List<List<Object>> dataList(List<String> fieldList, JSONArray dataObj) {
        List<List<Object>> dataList = new ArrayList<>();
        for (Object dataObjValue : dataObj) {
            List<Object> data = new ArrayList<>();
            for (String field : fieldList) {
                data.add(((JSONObject) JSON.toJSON(dataObjValue)).get(field));
            }

            dataList.add(data);
        }
        return dataList;
    }
}
